package com.ruoyi.user.service.impl;

import cn.dev33.satoken.jwt.SaJwtUtil;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.DeviceType;

import com.ruoyi.common.satoken.utils.LoginHelper;
import com.ruoyi.user.domain.ApUser;
import com.ruoyi.user.domain.AppLoginForm;
import com.ruoyi.user.mapper.ApUserMapper;
import com.ruoyi.user.service.ApUserService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@RequiredArgsConstructor
@Service
@Slf4j
public class ApUserServiceImpl implements ApUserService {

    private final ApUserMapper baseMapper;
    @Override
    public R<Map<String, Object>> login(AppLoginForm appLoginForm) {


        if (!StringUtils.isBlank(appLoginForm.getPhone()) && !StringUtils.isBlank(appLoginForm.getPassword())) {

            ApUser apUser = baseMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, appLoginForm.getPhone()));
            if (apUser == null) {
                return R.fail(HttpStatus.UNAUTHORIZED, "认证失败，无法访问系统资源");
            }

            if(!BCrypt.checkpw(appLoginForm.getPassword(), apUser.getPassword())){
                return R.fail(HttpStatus.UNAUTHORIZED, "密码错误！");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("token", LoginHelper.login4News(apUser.getId(), DeviceType.APP));
            //清除敏感数据
            apUser.setPassword("");
            map.put("user", apUser);
            return R.ok(map);
        } else {
            //2.游客  同样返回token  id = 0
            Map<String, Object> map = new HashMap<>();
            map.put("token", LoginHelper.login4News(0, DeviceType.APP));
            return R.ok(map);
        }


    }

    @DS("old_db")
    @Override
    public void getOldUserList() {
        log.info("老用户数据--" + baseMapper.selectList());

    }


}
